use tokio::task;
use reqwest::Client;
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
use flume::{Sender, Receiver, bounded};
use futures::stream::{FuturesUnordered, StreamExt};
use std::time::Instant;

mod config;
mod generater;
mod sender;
mod monitor;
mod thread;

#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() {
    let client = Arc::new(Client::new());
    let (tx, rx) = bounded(1000);
    let total_counter = Arc::new(AtomicUsize::new(0));
    let success_counter = Arc::new(AtomicUsize::new(0));

    // 启动生产者和消费者
    let consumers = thread::start_consumers(rx.clone(), Arc::clone(&total_counter), Arc::clone(&success_counter), Arc::clone(&client)).await;
    let producers = thread::start_producers(tx.clone()).await;

    // 启动监控任务
    let monitor_handle = task::spawn(async move {
        monitor::monitor_requests(total_counter, success_counter, rx).await;
    });

    // // 等待一段时间后关闭生产者和消费者
    // tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;

    // // 关闭发送端以停止消费者
    // drop(tx);

    // 等待所有任务完成
    producers.for_each(|_| async {}).await;
    drop(tx);
    consumers.for_each(|_| async {}).await;

    // 监控任务不需要等待，因为它是一个无限循环
    // 在真实场景中，你可能需要一个机制来停止监控任务
    // let _ = monitor_handle.await;
}
